import { useRequest } from "@/.umi/plugin-request";
import { SYS_TITLE } from "@/constants";
import { login } from "@/services/login";
import { setToken, setUerInfo } from "@/utils/info";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { history } from "@umijs/max";
import { Button, Form, Input, message } from "antd";
import styles from "./index.less";

export default () => {
  const [form] = Form.useForm();
  const { run: loginFun } = useRequest(login, {
    manual: true, // 手动触发
    onSuccess: (res) => {
      if (res instanceof Error) return;
      setToken(res?.token);
      setUerInfo({
        userName: res?.nickname,
        account: res?.account,
      });
      message.success("登录成功");
      history.push("/");
    },
  });
  const onFinish = async (values: any) => {
    await form.validateFields();
    loginFun({
      ...values,
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.loginForm}>
        <div className={styles.title}>{SYS_TITLE}</div>
        <div className={styles.loginContent}>
          <Form form={form} onFinish={onFinish}>
            <Form.Item
              name="username"
              rules={[{ required: true, message: "请输入账号" }]}
            >
              <Input prefix={<UserOutlined />} placeholder="账号" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="密码" />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ width: "100%" }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};
